package com.andyou.rest.service;

import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.andyou.common.service.CrudService;
import com.andyou.modules.sys.entity.User;
import com.andyou.modules.sys.service.SystemService;
import com.andyou.rest.dao.AppSessionContextDao;
import com.andyou.rest.entity.AppInfo;
import com.andyou.rest.entity.AppSessionContext;

@Service
@Transactional(readOnly = true)
public class AppSessionContextService extends CrudService<AppSessionContextDao, AppSessionContext> {

	@Autowired
	private AppSessionContextDao appSessionContextDao;
	@Autowired
	private SystemService systemService;

	/**
	 * 初始化用户信息
	 * 
	 * @param accessToken
	 *            （参数不可空）
	 * @return 返回null时表示accessToken 失效，需要重新登录
	 * @author lgx Date:2017年4月22日；
	 */
	@Transactional(readOnly = false)
	public User initUser(String accessToken) {
		User user = null;
		AppSessionContext appSessionContext = super.get(accessToken);
		
		Date nowDate = new Date();
		//说明accessToken已经失效
		if (nowDate.after(appSessionContext.getExpiredDate())) {
			return null;
		}
		
		if (appSessionContext != null) {
			user = systemService.getUserByLoginName(appSessionContext.getAccount());
		}
		
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(Calendar.MINUTE, 30);
		appSessionContext.setExpiredDate(nowTime.getTime());
		appSessionContextDao.update(appSessionContext);
		
		return user;
	}

	/**
	 * 插入上下文
	 * 
	 * @param appInfo
	 *            参数不可空
	 * @param user
	 *            参数不可空
	 * @param accessToken
	 *            参数不可空
	 * @return
	 * @author lgx Date:2017年4月20日；
	 */
	@Transactional(readOnly = false)
	public void insertByappInfoAnduser(AppInfo appInfo, User user, String accessToken) {

		AppSessionContext appSessionContext = new AppSessionContext();
		appSessionContext.setAccessToken(accessToken);
		appSessionContext.setAccount(user.getLoginName());
		appSessionContext.setCompanyId(user.getCompany().getId());
		appSessionContext.setCompanyName(user.getCompany().getName());
		appSessionContext.setOfficeId(user.getOffice().getId());
		appSessionContext.setOfficeName(user.getOffice().getName());
		appSessionContext.setUpdateBy(user);
		appSessionContext.setCreateBy(user);
		appSessionContext.setCreateDate(new Date());
		appSessionContext.setUpdateDate(new Date());
		appSessionContext.setLoginDate(new Date());

		appSessionContext.setId(accessToken);// 将id和accessToken设置一样，方便查询

		// 30分钟后过期
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(Calendar.MINUTE, 30);//
		appSessionContext.setExpiredDate(nowTime.getTime());

		appSessionContextDao.insert(appSessionContext);

	}

}
